package com.yong.sbd.common.beans.handle;

import com.yong.sbd.common.beans.exception.BusinessException;
import com.yong.sbd.common.beans.response.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 异常统一处理
 *
 * @author Kang Yong
 * @date 2025/10/24
 * @since 1.0.0
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class BusinessExceptionHandle {

    private final HttpServletRequest request;

    @ExceptionHandler(value = BusinessException.class)
    public R<Void> businessException(BusinessException e) {
        log.error("[businessException]代码执行报错：业务异常");
        return R.error(e);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Void> vaildDataException(MethodArgumentNotValidException e) {
        log.error("[vaildDataException]代码执行报错：参数校验异常");
        List<FieldError> fieldErrors = e.getFieldErrors();
        return this.assembMsg(fieldErrors);
    }

    @ExceptionHandler(value = Exception.class)
    public R<Void> exception(Exception e) {
        log.error("[exception]代码执行报错");
        return R.error(e.getMessage());
    }

    /**
     * 格式化异常信息
     *
     * @param fieldErrors {@link List< FieldError>}
     * @return {@link R< Void>}
     * @author KangYong
     * @date 2025/10/24
     */
    private R<Void> assembMsg(List<FieldError> fieldErrors) {
        if ("GET".equals(request.getMethod())) {
            return R.error(fieldErrors.get(0).getDefaultMessage());
        }
        if ("POST".equals(request.getMethod())) {
            if (!CollectionUtils.isEmpty(fieldErrors)) {
                Map<String, String> msgMap = new HashMap<>();
                fieldErrors.forEach(fieldError -> msgMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
                return R.formError(msgMap);
            }
        }
        return null;
    }
}
